package org.edu.modules.stu.base.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.edu.common.base.PageDto;
import org.edu.common.dto.ExcelPo;
import org.edu.common.utils.FilePo;
import org.edu.common.utils.FileUpload;
import org.edu.common.utils.PoiUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.modules.stu.base.entity.VeStuFile;
import org.edu.modules.stu.base.service.VeStuFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = {"文件信息"})
@RestController
@RequestMapping("/stu/veStuFile")
@Slf4j
public class VeStuFileController {

    @Autowired
    private VeStuFileService hqFileService;

    @AutoLog(value = "查询")
    @ApiOperation(value = "查询", notes = "查询")
    @GetMapping(value = "/list")
    public Result<?> queryById(@RequestParam(name = "id", required = false) String id,
                               @RequestParam(name = "serviceId", required = false) String serviceId,
                               @RequestParam(name = "serviceType", required = false) String serviceType) {
        LambdaUpdateWrapper<VeStuFile> queryWrapper = new LambdaUpdateWrapper<>();
        if (StrUtil.isEmpty(id)) {
            queryWrapper.eq(VeStuFile::getServiceId, serviceId);
            queryWrapper.eq(VeStuFile::getServiceType, serviceType);
        } else {
            queryWrapper.eq(VeStuFile::getId, id);
        }
        List<VeStuFile> list = hqFileService.listByWrapper(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 上传到服务器
     */
    @AutoLog(value = "上传到服务器")
    @ApiOperation(value = "上传", notes = "上传")
    @RequestMapping("/upload")
    public Result<?> uploadServcer(@RequestParam(value = "file", required = false) MultipartFile file,
                                   String BASE64, String fileName, String serviceId, String serviceType, HttpServletRequest request) {
        VeStuFile po = new VeStuFile();
        try {
            //todo 排查 上传附件接口报错，文件读取失败
            if (StrUtil.isEmpty(serviceType)) {
                serviceType = "common";
            }
            FilePo file1 = null;
            if (file == null) {
                file1 = FileUpload.uploadBASE64(BASE64, fileName, request, serviceType);
            } else {
                file1 = FileUpload.uploadFile1(file, request, serviceType);
            }
            if (file1 != null) {
                po.setPath(file1.getWebPath());
                po.setExt(file1.getExt());
                po.setFileName(file1.getName());
                po.setName(file1.getUploadName());
            }
            po.setServiceId(serviceId);
            po.setServiceType(serviceType);
            hqFileService.insert(po);
        } catch (IOException e) {
            e.printStackTrace();

            return Result.error("文件读取失败："+e.getMessage());
        }
        return Result.OK(po);
    }

    /**
     * 下载文件
     */
    @AutoLog(value = "下载文件")
    @ApiOperation(value = "下载文件", notes = "下载文件")
    @GetMapping("/download")
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        VeStuFile appFile = hqFileService.findById(id);
        String realName;
        try {
            realName = new String(appFile.getName().getBytes(), "ISO8859_1");
            download(response, realName, appFile.getPath());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    public static void download(HttpServletResponse response, String realName, String downloadPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(downloadPath);
        response.setHeader("Content-disposition", "attachment; filename=" + realName);
        try {
            bis = new BufferedInputStream(new FileInputStream(f));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead = 0;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                //bos.write(new byte[]{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
